﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Components
{
    public class QueryStringHelper
    {
        public static TValue Get<TValue>(string key, TValue defaultValue = default(TValue))
        {
            var val = HttpContext.Current.Request.QueryString[key];
            if( val != null )
            {
                return (TValue) Convert.ChangeType(val, typeof (TValue));
            }

            return defaultValue;
        }


        public static string PatchUrl(params object[] parameters)
        {
            var request = HttpContext.Current.Request;

            var newData = request.QueryString.AllKeys.ToDictionary(
                    k=>k,
                    k=>request.QueryString[k]
                );
            

            var ctx = request;
            for (int i = 0; i < parameters.Length; i += 2)
            {
                newData[(string) parameters[i]] = parameters[i + 1].ToString();
            }

            foreach (var empty in newData.Where(x => x.Value == null).Select(x => x.Key).ToList())
            {
                newData.Remove(empty);
            }


            var sb = new StringBuilder("?");            
            foreach( var kv in newData )
            {
                if( sb.Length > 1 )
                {
                    sb.Append("&");
                }
                sb.Append(HttpUtility.UrlEncode(kv.Key))
                    .Append("=")
                    .Append(HttpUtility.UrlEncode(kv.Value));
            }

            return sb.ToString();
        }

    }
}